<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */

namespace app\command\ocean;

use app\command\BaseWork;
use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\service\fetch\OceanFetchService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class TrackUrlSyncWork extends BaseWork
{
    public const REDIS_TASK_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_KEY]['track_url'];

    protected function configure()
    {
        // 指令配置
        $this->setName('oe_track_url_sync_work');
        // 设置参数
        $this->setDescription('拉取同步巨量事件资产下的监测链接组');

        // 设置参数
        $this->addArgument('advertiser_id', null, '账户id')
            ->setHelp('php think oe_track_url_sync_work [advertiser_id]');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $this->getOutputMessage('拉取同步巨量事件资产下的监测链接组开始');
        $redisKey = self::REDIS_TASK_KEY;
        $redis = Cache::store('redis')->handler();

        $st = time() + 5 * 60;
        while (time() < $st) {
            try {
                $advertiserId = $redis->lPop($redisKey);
                if (! $advertiserId) {
                    usleep(500000);
                    continue;
                }
                $res = OceanFetchService::fetchTrackUrlList($advertiserId);
                if (! $res) {
                    $this->getOutputMessage('拉取同步巨量事件资产下的监测链接组失败,账户id:' . $advertiserId . OceanFetchService::getError(0));
                }
            } catch (\Exception $e) {
                $this->getOutputMessage($e->getMessage());
                $this->getOutputMessage($e->getFile() . '[' . $e->getLine() . ']');
                $this->getOutputMessage($e->getTraceAsString());
            }
        }

        $this->getOutputMessage('拉取同步巨量事件资产下的监测链接组结束');
    }
}
